<?php
/**
 * Created by PhpStorm.
 * User: wanzengchuang
 * Date: 2017/10/10
 * Time: 22:15
 */

namespace asyncService\lib;

use asyncService\Bootstrap;

class log
{
    static $filter = [];

    static $instances ;

    /**
     * @param bool $key
     * @return mixed
     * @throws \notSetConfig
     */
    static function getInstance($key =false){
        if($key == false){
            $key = "main";
        }
        if(!isset(self::$instances[$key])){
            $logConfig = Bootstrap::getInstance()->getConfig('log');
            if(!isset($logConfig['store'])){
               throw new \notSetConfig();
            }
            $store = $logConfig['store'];
            self::$filter = isset($logConfig['filter'])?$logConfig['filter']:[];
            self::$instances[$key] = new static($store,$key);
        }

        return self::$instances[$key];
    }

    protected $store;
    protected $filename;

    public function __construct($store,$filename)
    {
        $this->store  = $store;
        $this->filename = $filename.".log";

        $old_file = $this->store.$this->filename;
        if(file_exists($old_file)){
            $i = 1;
            while($i>0){
                $new_filename = $old_file.".".$i;
                if(!file_exists($new_filename)){
                    if(!@rename($old_file,$new_filename)){
                        throw new \Exception("没有权限移动{$old_file}");
                    }
                    $i=0;
                }else{
                    $i++;
                }

            }
        }
    }

    function info($string){
        if(!in_array("info",self::$filter)){
            return ;
        }
        $time = time();
	    $pid = getmypid();
        $this->write("['info'][$time][$pid]".$string);
    }

    function debug($string){
        if(!in_array("debug",self::$filter)){
            return ;
        }
        $time = time();
	    $pid = getmypid();
        $this->write("['debug'][$time][$pid]".$string);
    }

    function warn($string){
        if(!in_array("warn",self::$filter)){
            return ;
        }
        $time = time();
        $pid = getmypid();
        $this->write("['warn'][$time][$pid]".$string);
    }

    function write($fileContent){
        @file_put_contents($this->store.$this->filename, $fileContent."\n", FILE_APPEND);
    }
}